﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace LiteExpress.Utilities.TypeExtension
{
    public static class TypeExtension
    {
        public static short ToShort(this string str, short defaultValue = 0)
        {
            if (string.IsNullOrWhiteSpace(str)) return defaultValue;
            short result;
            return short.TryParse(str, out result) ? result : defaultValue;
        }

        public static int ToInt(this string str, int defaultValue = 0)
        {
            if (string.IsNullOrWhiteSpace(str)) return defaultValue;
            int result;
            return int.TryParse(str, out result) ? result : defaultValue;
        }

        public static long ToLong(this string str)
        {
            if (string.IsNullOrWhiteSpace(str)) return 0;
            long result;
            return long.TryParse(str, out result) ? result : 0;
        }

        //public static string ToShareCodeText(this string str, string codeName)
        //{
        //    long codeID = 0;
        //    long.TryParse(str, out codeID);
        //    var code = Cloud.ShareCode.CodeClass.GetCodeItem(codeName, codeID);
        //    return code == null ? "" : code.CodeNameCn;
        //}

        public static long ToUnixTimeStamp(this DateTime input)
        {
            return (input.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000;
        }

        public static long ToUnixTimeStamp(this string input)
        {
            DateTime dt;

            if (string.IsNullOrWhiteSpace(input))
            {
                return 0;
            }

            if (!DateTime.TryParse(input, out dt))
            {
                return 0;
            }

            return (dt.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks) / 10000;
        }

        public static bool IsNullOrEmpty(this string input)
        {
            return string.IsNullOrWhiteSpace(input);
        }

        public static bool IsNotNullOrEmpty(this string input)
        {
            return !string.IsNullOrWhiteSpace(input);
        }

        public static DateTime? ToDateTimeWithNull(this string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return null;
            }

            DateTime result;
            return DateTime.TryParse(input, out result) ? (DateTime?)result : null;
        }

        public static DateTime ToDateTime(this string input)
        {
            var defaultvalue = DateTime.Parse("1900-1-1");

            if (string.IsNullOrWhiteSpace(input))
            {
                return DateTime.Parse("1900-1-1");
            }

            DateTime result;
            if (!DateTime.TryParse(input, out result))
            {
                result = defaultvalue;
            }

            return result;
        }

        public static string Fmt(this string input, params object[] args)
        {
            return string.Format(input, args);
        }

        public static string RemoveSqlKeywords(this string input)
        {
            //删除脚本
            input = Regex.Replace(input, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            input = Regex.Replace(input, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"-->", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"<!--.*", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "xp_cmdshell", "", RegexOptions.IgnoreCase);

            //删除与数据库相关的词
            input = Regex.Replace(input, "select", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "insert", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "delete from", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "count''", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "drop table", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "truncate", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "asc", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "mid", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "char", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "xp_cmdshell", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "exec master", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "net localgroup administrators", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "and", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "net user", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "or", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "net", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "-", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "delete", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "drop", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "script", "", RegexOptions.IgnoreCase);

            //特殊的字符
            input = input.Replace("<", "");
            input = input.Replace(">", "");
            input = input.Replace("*", "");
            input = input.Replace("-", "");
            input = input.Replace("?", "");
            input = input.Replace("'", "''");
            input = input.Replace("/", "");
            input = input.Replace(";", "");
            input = input.Replace("*/", "");
            input = input.Replace("\r\n", "");

            return input;
        }

        public static string Left(this string input, int length, string defaultValue = null)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return defaultValue;
            }

            if (input.Length <= length)
            {
                return input;
            }

            return input.Remove(length);
        }

        /// <summary>
        /// 获取字符串的真实长度，中文算两个字节长度
        /// </summary>        
        public static int GetCnLength(this string input)
        {
            int len = 0;
            for (int i = 0; i < input.Length; i++)
            {
                byte[] byte_len = Encoding.UTF8.GetBytes(input.Substring(i, 1));
                if (byte_len.Length > 1)
                    len += 2; //如果长度大于1，是中文，占两个字节，+2
                else
                    len += 1;  //如果长度等于1，是英文，占一个字节，+1
            }

            if (len % 2 == 1)
            {
                len++;
            }
            len = len / 2;
            return len;
        }

        /// <summary>
        /// 截取固定长度的字符串，中文算两个字节长度
        /// </summary>        
        public static string LeftCn(this string input, int length, string defaultValue = null)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return defaultValue;
            }

            int tmplen = 0;
            for (int i = 0, len = input.Length; i < len; i++)
            {
                byte[] byte_len = Encoding.UTF8.GetBytes(input.Substring(i, 1));
                if (byte_len.Length > 1)
                    tmplen += 2; //如果长度大于1，是中文，占两个字节，+2
                else
                    tmplen += 1;  //如果长度等于1，是英文，占一个字节，+1

                if (tmplen >= length * 2)
                {
                    return input.Substring(0, i + 1);
                }
            }

            return input;
        }

        /// <summary>
        /// 去除Html标签字符串
        /// </summary>
        public static string RemoveHTML(this string Htmlstring)
        {
            //删除脚本 
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML 
            Htmlstring = Regex.Replace(Htmlstring, @"<br>", "$br$", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"$br$", "<br>", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "<br>", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            // Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            return Htmlstring;
        }        

        public static string ToTextCh(this TimeSpan input)
        {
            var result = new StringBuilder();
            if (input.Days > 0) 
            {
                result.AppendFormat("{0}天", input.Days);
            }

            if (input.Hours > 0)
            {
                result.AppendFormat("{0}小时", input.Hours);
            }

            if (input.Minutes > 0)
            {
                result.AppendFormat("{0}分钟", input.Minutes);
            }

            return result.ToString();
        }

        public static bool IsEmail(this string input)
        {
            return ValidateHelper.IsEmail(input);
        }

        public static bool IsMobile(this string input)
        {
            return ValidateHelper.IsMobile(input);
        }

        public static bool IsIP(this string input)
        {
            return ValidateHelper.IsIP(input);
        }

        public static long GetHashNumber(this string input)
        {
            byte[] data = Encoding.UTF8.GetBytes(input);
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(data);
            var ret = BitConverter.ToInt64(hash, 0);
            return ret;
        }

        /// <summary>
        /// 获取邮件地址对应的邮箱服务商站点地址(包含Http)
        /// </summary>
        public static string GetEmailSite(this string email)
        {
            if (!ValidateHelper.IsEmail(email))
            {
                return string.Empty;
            }

            string emailsuffix = email.Split('@')[1];
            string email_url = string.Empty;
            switch (emailsuffix)
            {
                case "163.com":
                    email_url = "http://mail.163.com/";
                    break;
                case "126.com":
                    email_url = "http://mail.126.com/";
                    break;
                case "qq.com":
                    email_url = "https://mail.qq.com/cgi-bin/loginpage";
                    break;
                case "sina.com":
                    email_url = "http://mail.sina.com.cn/";
                    break;
                case "gmail.com":
                    email_url = "https://accounts.google.com/ServiceLogin?service=mail";
                    break;
                case "vip.163.com":
                    email_url = "http://vip.163.com/";
                    break;
                case "vip.126.com":
                    email_url = "http://vip.126.com/";
                    break;
                case "188.com":
                    email_url = "http://188.com/";
                    break;
                case "139.com":
                    email_url = "http://mail.10086.cn/";
                    break;
                case "yeah.net":
                    email_url = "http://www.yeah.net/";
                    break;
                case "Vip.sina.com":
                    email_url = "http://vip.sina.com.cn/";
                    break;
                case "sina.cn":
                    email_url = "http://mail.sina.com.cn/";
                    break;
                case "wo.com.cn":
                    email_url = "http://mail.wo.com.cn/mail/login.action";
                    break;
                case "189.cn":
                    email_url = "http://webmail23.189.cn/webmail/";
                    break;
                case "hotmail.com":
                    email_url = "https://login.live.com/";
                    break;
                default:
                    email_url = "http://mail." + emailsuffix;
                    break;
            }
            return email_url;
        }
    }
}
